import 'package:easy_refresh/easy_refresh.dart';
import 'package:get/get.dart';
import 'package:infinite_scroll_pagination/infinite_scroll_pagination.dart';
import 'package:pornhub_app/components/diolog/loading/loading_view.dart';
import 'package:pornhub_app/http/api/api.dart';
import 'package:pornhub_app/http/http_service.dart';
import 'package:pornhub_app/model/community/community_model.dart';
import 'package:pornhub_app/model/user/user_info_model.dart';
import 'package:pornhub_app/services/user_service.dart';
import 'package:pornhub_app/utils/logger.dart';

class UserHomePageController extends GetxController {
  final userService = Get.find<UserService>();
  final EasyRefreshController refreshController = EasyRefreshController();
  final PagingController<int, CommunityModel> pagingControllers =
      PagingController(firstPageKey: 1);
  int userId = 0;
  int pageIndex = 1;
  Rx<UserInfo> userInfo = UserInfo().obs;

  @override
  void onInit() {
    final arguments = Get.arguments;
    if (arguments != null) {
      userId = Get.arguments['userId'] ?? 0;
    }
    super.onInit();
  }

  @override
  onReady() {
    super.onReady();
    LoadingView.singleton.wrap(
        context: Get.context!,
        asyncFunction: () async {
          getHttpData(isRefresh: true);
        });
  }

  getHttpData({required bool isRefresh}) {
    if (isRefresh) {
      getUserInfo();
      getUserDynamicLists(isRefresh: isRefresh);
    } else {
      getUserDynamicLists(isRefresh: isRefresh);
    }
  }

  ///获取用户信息
  getUserInfo() {
    try {
      httpInstance
          .get(
              url: "user/getUserInfo",
              queryMap: {"userId": userId},
              complete: UserInfo.fromJson)
          .then((response) {
        if (response is UserInfo) {
          userInfo.value = response;
        }
      });
    } catch (e) {
      logger.e(e);
    }
  }

  ///获取用户动态列表
  getUserDynamicLists({required bool isRefresh}) {
    pageIndex = isRefresh ? 1 : pageIndex++;
    Api.getUserDynamicLists(userId: userId, page: pageIndex).then((response) {
      if (response.isNotEmpty) {
        if (isRefresh) {
          pagingControllers.refresh();
        }
        pagingControllers.appendPage(response, pageIndex);
      } else {
        pagingControllers.appendLastPage([]);
      }
    });
  }

  ///关注用户和取消关注
  attentionUser() {
    LoadingView.singleton.wrap(
        context: Get.context!,
        asyncFunction: () async {
          if (userInfo.value.attention == true) {
            await Api.cancelAttentionUser(userId);
          } else {
            await Api.attentionUser(userId);
          }
          getUserInfo();
        });
  }
}
